package com.tencent.cloud.iov.util;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * @author vinsonhuang
 * @date 2018/8/9
 */
public class ViewUtils {

    public static void handleBackClick(final Activity activity, View view) {
        if (null == activity || null == view) {
            return;
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });
    }

    /**
     * @param rootView   根布局
     * @param bottomView 需要显示的最下方View
     */
    public static void addLayoutListener(final View rootView, final View bottomView) {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        //1、获取main在窗体的可视区域
                        rootView.getWindowVisibleDisplayFrame(rect);
                        //2、获取main在窗体的不可视区域高度，在键盘没有弹起时，
                        // rootView.getRootView().getHeight()调节度应该和rect.bottom高度一样
                        int mainInvisibleHeight = rootView.getRootView().getHeight() - rect.bottom;
                        //屏幕高度
                        int screenHeight = rootView.getRootView().getHeight();
                        //3、不可见区域大于屏幕本身高度的1/4，说明键盘弹起了
                        if (mainInvisibleHeight > screenHeight / 4) {
                            int[] location = new int[2];
                            bottomView.getLocationInWindow(location);
                            // 4､获取Scroll的窗体坐标，算出main需要滚动的高度
                            int scrollHeight = (location[1] + bottomView.getHeight()) - rect.bottom;
                            //5､让界面整体上移键盘的高度
                            rootView.scrollTo(0, scrollHeight);
                        } else {
                            //3、不可见区域小于屏幕高度1/4时,说明键盘隐藏了，把界面下移，移回到原有高度
                            rootView.scrollTo(0, 0);
                        }
                    }
                });
    }

}
